import axios from 'axios';
import router from '../router';
import i18n, { getLanguage } from '../lang'
import { processI18nKeys } from '../utils';
import AuthUtils from '@/utils/auth';

// 请求地址
// export const url = "/api"

// 创建axios实例
const request = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // api的base_url
	// baseURL:'/api',
	timeout: 50000 // 请求超时时间
});

// 请求拦截器
request.interceptors.request.use(
	config => {
		let token = localStorage.getItem("token");
		let lang = getLanguage();
		// let lang = 'cht';
		config.headers['Authorization'] = token;
		config.headers['token'] = token;
		config.headers['lang'] = lang;
		config.headers['accept-language'] = lang;
		config.headers['X-Requested-With'] = 'XMLHttpRequest';
		if (!config.headers['Content-Type']) {
			config.headers['Content-Type'] = 'application/json';
		}
		let obj = config.data || {}
		obj.token = token;
		config.data = obj;
		// 可以在这里添加请求头等信息
		return config;	
	},
	error => {
		// 请求错误处理
		Promise.reject(error);
	}
);

let responseCallback = {}

/**
 * 设置响应回调函数
 * @param {*} key 以/开头的请求路径作为key
 * @param {*} callback 回调函数
 */
export function setResponseCallback(key, callback){
	if (typeof callback === 'function') {
		responseCallback[key] = callback;
	}
}

export function removeResponseCallback(key){
	if (responseCallback[key]) {
		delete responseCallback[key];
	}
}

// 响应拦截器
request.interceptors.response.use(
	response => {
		// 处理错误码
		const handlerResult = errorCodeHandler(response.data.code);
        if (handlerResult !== undefined) {
            return handlerResult;
        }

		// 对响应数据做处理，例如只返回data部分
		const res = response.data;
		let i18nMessage = i18n.locale
		res.data = processI18nKeys(res.data , i18nMessage)
		console.log(i18nMessage , res, 'i18nMessage')
		// 根据返回的状态码做相应处理，例如401未授权等
		

		const rawUrl = response.config.url;
		const subPath = rawUrl.split('?')[0];
		let callback = responseCallback[subPath]
		if (callback) {
			try {
				callback(res);
			} catch (error) {
				console.error(`Error in response callback for ${subPath}:`, error);
			}
		}	

		return res;
	},
	error => {
		// 响应错误处理
		if (error.code === 'ERR_NETWORK') {
			console.error('网络连接失败，请检查：');
			console.error(`1. 服务 ${error.config.baseURL} 是否运行`);
			console.error('2. 网络是否通畅');
			console.error('3. 是否配置了正确的CORS');
		}

		const handlerResult = errorCodeHandler(error.response?.status);
        if (handlerResult !== undefined) {
            return handlerResult;
        }

		return Promise.reject(error);
	}
);

function errorCodeHandler(code) {
    switch (code) {
        case 401:
			AuthUtils.logout();
			localStorage.removeItem('token');
			return Promise.reject(new Error('token过期'));
        case 403:
            return
        case 404:
			return;
        case 405:
			return;
        case 406:
            return;
        case 407:
            return;
        default:
            return;
    }
}

export default request;